<template>
  <div class="rich-text-editor">
    <div ref="editorRef" class="editor-container"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch, nextTick } from 'vue'
import Quill from 'quill'
import 'quill/dist/quill.snow.css'

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  placeholder: {
    type: String,
    default: '请输入内容...'
  },
  height: {
    type: String,
    default: '300px'
  },
  readonly: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:modelValue', 'change'])

const editorRef = ref(null)
let quillInstance = null

// Quill配置
const quillOptions = {
  theme: 'snow',
  placeholder: props.placeholder,
  readOnly: props.readonly,
  modules: {
    toolbar: [
      [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
      [{ 'font': [] }],
      [{ 'size': ['small', false, 'large', 'huge'] }],
      ['bold', 'italic', 'underline', 'strike'],
      [{ 'color': [] }, { 'background': [] }],
      [{ 'script': 'sub' }, { 'script': 'super' }],
      [{ 'list': 'ordered' }, { 'list': 'bullet' }],
      [{ 'indent': '-1' }, { 'indent': '+1' }],
      [{ 'direction': 'rtl' }],
      [{ 'align': [] }],
      ['link', 'image', 'video'],
      ['clean']
    ]
  }
}

// 初始化编辑器
const initEditor = () => {
  if (editorRef.value) {
    quillInstance = new Quill(editorRef.value, quillOptions)
    
    // 设置编辑器高度
    const editorContainer = editorRef.value.querySelector('.ql-editor')
    if (editorContainer) {
      editorContainer.style.minHeight = props.height
    }
    
    // 设置初始内容
    if (props.modelValue) {
      // 清理初始内容，去除多余的p标签包装
      let cleanValue = props.modelValue
      if (cleanValue.startsWith('<p>') && cleanValue.endsWith('</p>')) {
        const innerContent = cleanValue.slice(3, -4).trim()
        if (!/<[^>]+>/.test(innerContent)) {
          cleanValue = innerContent
        }
      }
      quillInstance.root.innerHTML = cleanValue
    }
    
    // 监听内容变化
    quillInstance.on('text-change', () => {
      const html = quillInstance.root.innerHTML
      const text = quillInstance.getText().trim()
      
      // 如果只有空白字符，则返回空字符串
      if (!text) {
        emit('update:modelValue', '')
        emit('change', '')
        return
      }
      
      // 清理HTML内容，去除多余的p标签包装
      let cleanHtml = html
      
      // 如果内容被p标签包装且没有其他格式，则提取纯文本
      if (cleanHtml.startsWith('<p>') && cleanHtml.endsWith('</p>')) {
        const innerContent = cleanHtml.slice(3, -4).trim()
        // 检查是否包含其他HTML标签
        if (!/<[^>]+>/.test(innerContent)) {
          cleanHtml = innerContent
        }
      }
      
      // 如果内容为空或只有空白字符，返回空字符串
      if (!cleanHtml.trim()) {
        cleanHtml = ''
      }
      
      emit('update:modelValue', cleanHtml)
      emit('change', cleanHtml)
    })
  }
}

// 监听modelValue变化
watch(() => props.modelValue, (newValue) => {
  if (quillInstance && newValue !== quillInstance.root.innerHTML) {
    // 清理新值，去除多余的p标签包装
    let cleanValue = newValue || ''
    if (cleanValue.startsWith('<p>') && cleanValue.endsWith('</p>')) {
      const innerContent = cleanValue.slice(3, -4).trim()
      if (!/<[^>]+>/.test(innerContent)) {
        cleanValue = innerContent
      }
    }
    quillInstance.root.innerHTML = cleanValue
  }
})

// 监听只读状态变化
watch(() => props.readonly, (newValue) => {
  if (quillInstance) {
    quillInstance.enable(!newValue)
  }
})

onMounted(() => {
  nextTick(() => {
    initEditor()
  })
})

onBeforeUnmount(() => {
  if (quillInstance) {
    quillInstance = null
  }
})

// 暴露方法
defineExpose({
  getQuill: () => quillInstance,
  getHTML: () => {
    if (!quillInstance) return ''
    const html = quillInstance.root.innerHTML
    const text = quillInstance.getText().trim()
    
    if (!text) return ''
    
    // 清理HTML内容，去除多余的p标签包装
    let cleanHtml = html
    
    // 如果内容被p标签包装且没有其他格式，则提取纯文本
    if (cleanHtml.startsWith('<p>') && cleanHtml.endsWith('</p>')) {
      const innerContent = cleanHtml.slice(3, -4).trim()
      // 检查是否包含其他HTML标签
      if (!/<[^>]+>/.test(innerContent)) {
        cleanHtml = innerContent
      }
    }
    
    return cleanHtml.trim() || ''
  },
  getText: () => quillInstance?.getText() || '',
  setHTML: (html) => {
    if (quillInstance) {
      quillInstance.root.innerHTML = html
    }
  },
  focus: () => quillInstance?.focus(),
  blur: () => quillInstance?.blur()
})
</script>

<style scoped>
.rich-text-editor {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
}

.rich-text-editor:hover {
  border-color: #c0c4cc;
}

.rich-text-editor:focus-within {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

:deep(.ql-toolbar) {
  border: none;
  border-bottom: 1px solid #e4e7ed;
  background-color: #fafafa;
}

:deep(.ql-container) {
  border: none;
  font-size: 14px;
  line-height: 1.6;
}

:deep(.ql-editor) {
  padding: 12px 15px;
  color: #606266;
}

:deep(.ql-editor.ql-blank::before) {
  color: #c0c4cc;
  font-style: normal;
}

/* 暗色模式支持 */








</style>